import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  // 示例方法
  ping: () => ipcRenderer.send('ping')
}

// 添加调试信息
console.log('Preload 脚本已加载')

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    console.log('Context isolation 已启用，使用 contextBridge')
    contextBridge.exposeInMainWorld('electron', {
      ipcRenderer: {
        // 发送消息到主进程
        send: (channel: string, ...args: any[]) => {
          console.log(`发送消息: ${channel}`, args)
          ipcRenderer.send(channel, ...args)
        },
        // 监听来自主进程的消息
        on: (channel: string, listener: (...args: any[]) => void) => {
          console.log(`注册监听器: ${channel}`)
          const subscription = (_event: Electron.IpcRendererEvent, ...args: any[]) => listener(...args)
          ipcRenderer.on(channel, subscription)
          return () => {
            console.log(`移除监听器: ${channel}`)
            ipcRenderer.removeListener(channel, subscription)
          }
        },
        // 发送消息到主进程并等待回复
        invoke: (channel: string, ...args: any[]) => {
          console.log(`调用方法: ${channel}`, args)
          return ipcRenderer.invoke(channel, ...args)
        },
        // 移除所有监听器
        removeAllListeners: (channel: string) => {
          console.log(`移除所有监听器: ${channel}`)
          ipcRenderer.removeAllListeners(channel)
        }
      },
      // 自定义API
      ...api
    })
    console.log('contextBridge 设置完成')
  } catch (error) {
    console.error('contextBridge 设置失败:', error)
  }
} else {
  console.log('Context isolation 未启用，直接添加到 window')
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}

console.log('Preload 脚本执行完成')
